package com.choosefine.it.team.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.choosefine.it.base.BaseController;
import com.choosefine.it.base.dto.DateDTO;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.json.JsonResult;
import com.choosefine.it.common.json.JsonUtil;
import com.choosefine.it.common.model.CustomRestTemplate;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.IdsUtil;
import com.choosefine.it.common.utils.URLHandlerUtils;
import com.choosefine.it.team.model.AuthorizationPicture;
import com.choosefine.it.team.model.ItemInfo;
import com.choosefine.it.team.model.WorkerMoneyMgtDTO;
import com.choosefine.it.team.model.dto.TeamMoneyMgtSelectDTO;
import com.choosefine.it.team.model.po.TeamInfoParamesAdd;
import com.choosefine.it.team.model.po.TeamInfoParamesUpdate;
import com.choosefine.it.team.model.vo.ItemInfoVO;
import com.choosefine.it.team.model.vo.TeamMoneyMgtVO;
import com.choosefine.it.team.model.vo.TeamWorkerMoneyMgtVO;
import com.choosefine.it.team.service.AuthorizationPictureService;
import com.choosefine.it.team.service.ItemInfoService;
import com.github.pagehelper.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 11.25dzq 班组信息
 * @author Administrator
 *
 */
@Api(value="班组信息",description="董自齐")
@RestController
@RequestMapping("/team/itemInfo")
public class ItemInfoController extends BaseController{
	

	@Value("#{yaml.get('shopping.order.payableCount')}")
	public String payableCount;

	@Autowired
	CustomRestTemplate restTemplate;
	
	@Autowired
	private ItemInfoService itemInfoService;
	
	@Autowired
	private AuthorizationPictureService authorizationPictureService;
	

//	/**
//	 * 项目下的班组数量
//	 * 
//	 * @author liaozhanggen 2017年1月5日
//	 */
//	@ApiOperation(value="项目下的班组工人总数")
//	@RequestMapping(value="worker/count/{teamId}",method=RequestMethod.GET)
//	public int getWorkerNumByTeamId(@PathVariable(value="teamId")int teamId){
//		return itemInfoService.getWorkerNumByTeamId(teamId);
//	}
	
	@RequestMapping(value="/{userCode}",method=RequestMethod.GET,params="method=userCode")
	/**
	 * 11.25dzq 查看用户负责的班组
	 * @param userCode
	 * @param page
	 * @return
	 */
	@ApiOperation(value="用户负责的班组")
	public String selectByUserCode(@PathVariable("userCode")String userCode,PageDTO page){
		String result = null;
		if("".equals(userCode)||userCode==null){
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		Page<ItemInfo> list = itemInfoService.selectByuserCode(userCode, page);
		result = responseSuccess(list);
		return result;
	}
	
	/**
	 * 12.10查找某项目下的班组数量dzq
	 * @return
	 */
	@GetMapping(value="/count/{projectCode}")
	@ApiOperation(value="查找某项目下的班组数量dzq",response=Integer.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "projectCode", value = "项目code", required = false, dataType = "String", paramType = "path"),
		@ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "long", paramType = "query"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "long", paramType = "query"),
	})
	public String selectCountByProject(
			@PathVariable("projectCode")String projectCode,
			DateDTO date){
		if(projectCode==null ||"".equals(projectCode)){
			return responseFail("参数错误");
		}
		if(!timeJudge(date)){
			return responseFail("参数错误");
		}
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("projectCode", projectCode);
		map.put("startTime", date.getStartTime());
		map.put("endTime", date.getEndTime());
		return responseSuccess(itemInfoService.selectCountTeamByProject(map));
	}
	
	/**
	 * 12.23查找某项目下的班组dzq
	 * @return
	 */
	@GetMapping(value="/team/{projectCode}")
	@ApiOperation(value="查找某项目下的班组dzq",response=Integer.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "projectCode", value = "项目code", required = false, dataType = "String", paramType = "path"),
		@ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "long", paramType = "query"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "long", paramType = "query"),
		@ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "long", paramType = "query"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "long", paramType = "query")
	})
	public String getTeamListByProject(
			@PathVariable("projectCode")String projectCode,
			DateDTO date,
			PageDTO page){
		if(projectCode==null ||"".equals(projectCode)){
			return responseFail("参数错误");
		}
		if(!timeJudge(date)){
			return responseFail("参数错误");
		}
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("projectCode", projectCode);
		map.put("startTime", date.getStartTime());
		map.put("endTime", date.getEndTime());
		return responseSuccess(itemInfoService.getTeamListByProject(map,page));
	}
	
	/**
	 * @author chenjian
	 * @time 2016-12-12 下午7:44:51
	 */
	@ApiOperation(value="保存班组信息(陈健)",notes="控制台-项目管理-项目基本资料")
	@RequestMapping(value="/saveTeam",method=RequestMethod.POST,produces="application/json")
	public String saveTeam(@RequestBody TeamInfoParamesAdd teamInfoParamesAdd){
		String result=null;
		int teamId = itemInfoService.saveTeam(teamInfoParamesAdd);
		if(teamId>0){
			result = responseSuccess(teamId,ResultCode.SUCCESS,ResultCode.MSG_SUCCESS);
		}else {
			result = responseFail();
		}
		return result;
	}
	
	/**
	 * @author chenjian
	 * @time 2016-12-14 上午11:20:33
	 */
	@ApiOperation(value="更新班组信息(陈健)",notes="控制台-项目管理-项目基本资料")
	@RequestMapping(value="/updateTeam",method=RequestMethod.POST,produces="application/json")
	public String updateTeam(@RequestBody TeamInfoParamesUpdate teamInfoParamesUpdate){
		String result=null;
		int isSuccess = itemInfoService.updateTeam(teamInfoParamesUpdate);
		if(isSuccess>0){
			result = responseSuccess(isSuccess,ResultCode.SUCCESS,ResultCode.MSG_SUCCESS);
		}else {
			result = responseFail();
		}
		return result;
	}
	
	/**
	 * 
	 * @author chenjian
	 * @time 2016-12-15
	 */
	@ApiOperation(value="删除班组信息(陈健)",notes="控制台-项目管理-项目基本资料")
	@RequestMapping(value="/deleteTeam/{teamIdes}",method=RequestMethod.PUT,produces="application/json")
	@ApiImplicitParam(name = "teamIdes", value = "班组id字符串集合，id用逗号隔开", required = true, dataType = "String", paramType = "path")
	public String deleteTeam(@PathVariable String teamIdes) throws Exception{
		String result=null;
		if(com.choosefine.it.common.utils.StringUtils.isNotBlank(teamIdes)){
			Map<String, Object> paras = new HashMap<>();
			if(com.choosefine.it.common.utils.StringUtils.isNotBlank(teamIdes)){
				List<Integer> ides = IdsUtil.getIds(teamIdes);
				paras.put("ides", ides);
			}else{
				return responseFail(ResultCode.MSG_PARAMS_ERROR);
			}
			paras.put("utime", DateUtils.getNowTime());
			paras.put("isValid", CommonConstant.INVALID);
			int isSuccess = itemInfoService.deleteTeam(paras);
			if(isSuccess>0){
				result = responseSuccess(isSuccess,ResultCode.SUCCESS,ResultCode.MSG_SUCCESS);
			}else {
				result = responseFail();
			}
		}else {
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}
	
	/**
	 * @author chenjian
	 * @time 2016-12-16 下午5:23:42
	 */
	@ApiOperation(value="班组信息详情(陈健)",notes="控制台-项目管理-项目基本资料",response=ItemInfoVO.class)
	@RequestMapping(value="/teamDetail/{teamId}",method=RequestMethod.PUT,produces="application/json")
	@ApiImplicitParam(name = "teamId", value = "班组id", required = true, dataType = "int", paramType = "path")
	public String teamDetail(@PathVariable Integer teamId){
		String result=null;
		if(teamId!=null){
			AuthorizationPicture authorizationPicture = new AuthorizationPicture();
			authorizationPicture.setItemId(teamId);
			authorizationPicture.setItemType(2);
			authorizationPicture.setType(3);
			//查询分包班组承包人授权书
			List<String> authorizationList = authorizationPictureService.findPictureByItemId(authorizationPicture);
			ItemInfoVO itemInfoVO = itemInfoService.teamDetail(teamId);
			
//			List<TeamTypeRelationVO> teamTypeVOList = itemInfoService.teamTypeList(teamId);
			
			if(itemInfoVO!=null){
//				itemInfoVO.setTeamTypeRelationVOList(teamTypeVOList);
				itemInfoVO.setAuthorizationList(authorizationList);
				result = responseSuccess(itemInfoVO,ResultCode.SUCCESS,ResultCode.MSG_SUCCESS);
			}else {
				result = responseFail(ResultCode.MSG_DATA_ISEMPTY);
			}
		}else {
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}

	@ApiOperation(value="班组资金管理（鞠成阳）",notes="控制台-项目管理-班组资金管理",response=TeamMoneyMgtVO.class)
	@RequestMapping(value="/teamMoneyMgt",method=RequestMethod.POST)
	public String teamMoneyMgt(@RequestBody (required=false)TeamMoneyMgtSelectDTO tmmsDTO){
		String result = null;
		PageDTO pageDTO = new PageDTO();
		pageDTO.setPageNum(tmmsDTO.getPageNum());
		pageDTO.setPageSize(tmmsDTO.getPageSize());
		Map<String, Object>map = new HashMap<>();
		if(tmmsDTO.getProjectCode()!=null&&!"".equals(tmmsDTO.getProjectCode())){
			map.put("projectCode", tmmsDTO.getProjectCode());
		}
//		if(tmmsDTO.getTeamUserCode()!=null&&!"".equals(tmmsDTO.getTeamUserCode())){
//			map.put("teamUserCode", tmmsDTO.getTeamUserCode());
//		}
		if(tmmsDTO.getTeamUserName()!=null&&!"".equals(tmmsDTO.getTeamUserName())){
			map.put("teamUserName", tmmsDTO.getTeamUserName());
		}
		if(tmmsDTO.getProjectName()!=null&&!"".equals(tmmsDTO.getProjectName())){
			map.put("projectName", tmmsDTO.getProjectName());
		}
		Page<TeamMoneyMgtVO> resultMap = itemInfoService.selectTeamWorkerSalarySum(map, pageDTO);
		if(resultMap!=null){
			for(int i=0;i<resultMap.size();i++){
				resultMap.get(i).setMaterialMoneyAll(this.getTeamMoneyBy(resultMap.get(i).getProjectCode(), resultMap.get(i).getTeamId(), new Integer(1)));
				resultMap.get(i).setEquipmentMoneyAll(this.getTeamMoneyBy(resultMap.get(i).getProjectCode(), resultMap.get(i).getTeamId(), new Integer(2)));
				resultMap.get(i).setFacilityMoneyAll(this.getTeamMoneyBy(resultMap.get(i).getProjectCode(), resultMap.get(i).getTeamId(), new Integer(3)));
				if(resultMap.get(i).getWorkerSalarySum()==null){
					resultMap.get(i).setWorkerSalarySum(new BigDecimal(0));
				}
			}
			result = responseArraySuccess(resultMap.toPageInfo());
		}else{
			result = responseFail();
		}
		return result;
	}
	
	/**
     * 分步处理材料设备设施资金统计
     * @param projectCode
     * @param merchandiseType
     * @return
     */
    private BigDecimal getTeamMoneyBy(String projectCode,Integer teamId,Integer merchandiseType){

    	 if(projectCode != null && merchandiseType != null){
             StringBuffer CapitalUrl = URLHandlerUtils.getUrlBuffer(shoppingURL, payableCount)
                     .append("?projectCode=").append(projectCode).append("&merchandiseType=")
                     .append(merchandiseType).append("&teamId=").append(teamId);

             ResponseEntity<String> responseEntity = restTemplate.exchange(CapitalUrl.toString(),HttpMethod.GET, null, String.class);
             String resultString = responseEntity.getBody().toString();
             JsonResult result = JsonUtil.toObject(resultString,JsonResult.class);
             Double data = Double.valueOf(StringUtils.isEmpty(result.getData()) ? "0" : result.getData().toString());
             if (data == null)
                 return new BigDecimal(0.0);
             else
                 return new BigDecimal(data);
         }

         return new BigDecimal(0.0);
    }
	
	@ApiOperation(value="班组用户的挂靠公司（潘钱钦）",notes="")
	@RequestMapping(value="/selectTeamAffiliatedUnits/{userCode}",method=RequestMethod.GET,produces="application/json")
	@ApiImplicitParam(name = "userCode", value = "用户的userCode", required = true, dataType = "String", paramType = "path")
	public String selectTeamAffiliatedUnitsByUserCode(@PathVariable String userCode){
			List<String> affiliatedUnits = itemInfoService.selectTeamAffiliatedUnitsByUserCode(userCode);
			if(affiliatedUnits.size()>0){
				return responseArraySuccess(affiliatedUnits, ResultCode.SUCCESS, ResultCode.MSG_QUERY_SUCCESS);
			}else{
				return responseFail(ResultCode.FAILED, ResultCode.MSG_DATA_ISEMPTY);
			}
	}

	@ApiOperation(value = "班组工人工资管理（鞠成阳）", notes = "控制台-项目管理-班组资金管理-工人工资", response = TeamWorkerMoneyMgtVO.class)
	@RequestMapping(value = "/workerMoneyMgt", method = RequestMethod.POST)
	public String workerMoneyMgt(@RequestBody(required=false) WorkerMoneyMgtDTO wmmDTO) {
		String result = null;
		PageDTO pageDTO = new PageDTO();
		Map<String, Object> map = new HashMap<>();
		if(wmmDTO.getProjectCode()!=null&&wmmDTO.getTeamId()!=null){
			map.put("projectCode",wmmDTO.getProjectCode());
			map.put("teamId",wmmDTO.getTeamId());
			
			if (wmmDTO.getUserCode() != null && !"".equals(wmmDTO.getUserCode())) {
				map.put("userCode", wmmDTO.getUserCode());
			}
			if (wmmDTO.getUserName() != null && !"".equals(wmmDTO.getUserName())) {
				map.put("userName", wmmDTO.getUserName());
			}
			if (wmmDTO.getIdcardNum() != null && !"".equals(wmmDTO.getIdcardNum())) {
				map.put("idcardNum", wmmDTO.getIdcardNum());
			}
			if(wmmDTO.getPageNum()!=null){
				map.put("pageNum", wmmDTO.getPageNum());
			}
			if(wmmDTO.getPageSize()!=null){
				map.put("pageSize", wmmDTO.getPageSize());
			}
			if(wmmDTO.getMonth()!=null&&!"".equals(wmmDTO.getMonth())){
				map.put("month",wmmDTO.getMonth());
			}
			pageDTO.setPageNum(wmmDTO.getPageNum());
			pageDTO.setPageSize(wmmDTO.getPageSize());
			List<TeamWorkerMoneyMgtVO>resultList = itemInfoService.selectTeamWorkerSalaryBy(map,pageDTO);
			if(resultList!=null){
				for(int i=0;i<resultList.size();i++){
					resultList.get(i).setWorkerSalarySum(null==resultList.get(i).getWorkerSalarySum()?new BigDecimal(0):resultList.get(i).getWorkerSalarySum());
					resultList.get(i).setPayMoney(null==resultList.get(i).getPayMoney()? new BigDecimal(0):resultList.get(i).getPayMoney());
					resultList.get(i).setNotPayMoney(resultList.get(i).getWorkerSalarySum().subtract(resultList.get(i).getPayMoney()));
				}
				result = responseArraySuccess(resultList);
			}else{
				result = responseFail();
			}
		}else{
			result = responseFail();
		}
		return result;
	}
	
	/**
	 * @author chenjian
	 * @time 2016年12月30日下午3:15:20
	 * 根据分包承包人租户编号和项目编号查询班组
	 */
	@ApiOperation("根据分包承包人租户编号和项目编号查询班组(陈健)")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userCode", value = "班组租户编号", required = true, dataType = "String", paramType = "query"),
		@ApiImplicitParam(name = "projectCode", value = "项目编号", required = true, dataType = "String", paramType = "query")
	})
	@RequestMapping(value="/teamByCode",method=RequestMethod.GET)
	public  String findTeamByCode(@RequestParam String userCode,@RequestParam String projectCode) throws Exception{
		Map<String,Object> params = new HashMap<>();
		params.put("userCode", userCode);
		params.put("projectCode", projectCode);
		List<ItemInfo> itemInfoList = itemInfoService.findTeamByCode(params);
		if(itemInfoList.size()>0){
			return responseSuccess(1);
		}else{
			return responseSuccess(0);
		}
	}
	
	/**
	 * @author chenjian
	 * @time 2017年1月5日下午9:46:12
	 */
	@ApiOperation(value = "根据项目code获取班组信息(陈健)", notes = "商城调用接口", response = ItemInfo.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "projectCode", value = "项目code", required = true, dataType = "String", paramType = "query") })
	@RequestMapping(method = RequestMethod.GET, value = "/teamInfo")
	public String findTeamesByProjectCode(@RequestParam String projectCode) throws Exception {
		String result = null;
		Map<String, Object> map = new HashMap<>();
		map.put("projectCode", projectCode);
		map.put("isValid", 0);
		List<ItemInfo> list = itemInfoService.findTeamesByProjectCode(map);
		if (list.size() > 0) {
			result = responseSuccess(list);
		} else {
			result = responseFail(ResultCode.MSG_DATA_ISEMPTY);
		}
		return result;
	}
	
	
	/**
	 * @Description：校验同一项目同一分包承包人班组名不能重复(陈健)
	 * @Author：chenjian
	 * @Create Date：2017年2月25日
	 * @param：
	 * @return：   
	 */
	@ApiOperation(value = "校验同一项目同一分包承包人班组名不能重复(陈健)", notes = "控制台-项目基本信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "projectCode", value = "项目编号", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "userCode", value = "分包班组承包人租户编号", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "teamName", value = "班组名称", required = true, dataType = "String", paramType = "path")})
	@RequestMapping(method = RequestMethod.GET, value = "/teamName/{projectCode}/{userCode}/{teamName}")
	public String checkTeamName(@PathVariable String projectCode,@PathVariable String userCode,@PathVariable String teamName) throws Exception {
		String result = null;
		Map<String, Object> map = new HashMap<>();
		map.put("projectCode", projectCode);
		map.put("userCode", userCode);
		map.put("teamName", teamName);
		Integer flag = itemInfoService.checkTeamName(map);
		result = responseSuccess(flag);
		return result;
	}
	
}
